<template>
  <h3>vue3 + ts</h3>
  <button @click="minus">-</button>
  <span>{{ count }}</span>
  <button @click="add()">+</button>
  <button @click="add(3)">+</button>
  <span>{{ doubleCount }}</span>

  <hr />

  <input type="text" v-model="textValue" />
  <button @click="addItem">btn</button>
  <br />
  <ul>
    <li v-for="item in list" :key="item.id">
      {{ item.name }} - <button @click="removeItem(item.id)">删除</button>
    </li>
  </ul>

  <hr />

  <my-child :count="count" />
</template>

<script lang="ts">
import { defineComponent, ref, computed, ComputedRef, watch } from "vue";
import MyChild from "./components/MyChild.vue";

interface ListType {
  id: number;
  name: string;
}

export default defineComponent({
  setup() {
    // 泛型的语法,联合类型
    const count = ref<number>(5);
    // 函数参数的类型一定要加
    const add = (num?: number): void => {
      // console.log(num);
      if (num) {
        count.value += num;
      }
    };
    const minus = (): void => {
      count.value--;
    };

    // ComputedRef是vue给我们提供的ts类型
    const doubleCount = computed<number>(() => {
      return count.value * 2;
    });
    watch(count, (val): void => {
      console.log(val);
    });

    const list = ref<ListType[]>([
      {
        id: 1,
        name: "zhangsan",
      },
      {
        id: 2,
        name: "lisi",
      },
    ]);
    const textValue = ref<string>("");
    const addItem = (): void => {
      list.value.push({
        id: new Date().getTime(),
        name: textValue.value,
      });
      textValue.value = "";
    };
    const removeItem = (id: number): void => {
      list.value = list.value.filter((item) => item.id !== id);
    };

    return {
      count,
      add,
      minus,
      list,
      textValue,
      addItem,
      removeItem,
      doubleCount,
    };
  },
  components: {
    MyChild,
  },
});
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
